define(['moment'], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', "$datePicker",
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $datePicker) {

            $scope.init = function () {
                $scope.adjustInfo = {
                    reportdate: null,//moment(new Date()).format('YYYY-MM-DD'),
                    RWOMESNO: '',
                    LotNo: '',
                    OpNo: '',
                    MONo: '',
                    EquipmentNo: '',
                    SendResult_temp: 1,
                    adjustment_currently_main: [],
                    adjustment_currently_detail: [],
                    adjustment_currently_detail_ori: [],
                    adjustment_currently_record: [],
                    adjustment_currently_add: [],
                };
                $scope.clickItem = ''
                $scope.nowCondition = ''
                $scope.order_by_mode = {name:"",sort:false};
                $scope.PageConfig = {page : 0, page_count : 25};
            };
            $scope.C00_require_condition = true;
            $scope.codeList = [
                // 20240315 modify bt wenwei for M#149118: [sMES]日結調帳作業-ERP拋轉欄位需要有搜尋/篩選功能[台欣國際]
                {name:$filter('translate')('B1801.date'), column_name:'a.reportdate',   // 報工單日期
                value_s:new Date(), value_e:new Date(), data_type:'D'}, 
                {name:$filter('translate')('B1801.MONo'), column_name:'f.MONo'},    // 工單
                {name:$filter('translate')('B1801.rwomesno'), column_name:'a.RWOMESNO'},    // 報工單號
                {name:$filter('translate')('B1801.lotNo'), column_name:'a.LotNo'},  // 生產批
                {name:$filter('translate')('B1801.opNo'), column_name:'a.OpNo'},    // 作業站
                {name:$filter('translate')('B1801.equipment'), column_name:'a.EquipmentNo'},    // 設備
            ];
            $scope.back = function () {
                $scope.$root.changeProgram('home', true);
            };

            $scope.barcodeScan = function (event) {
                if (event.keyCode == 13) {
                    $scope.search();
                }
            };

            $scope.search = function (condition) {
                if ($scope.clickItem != '')
                    $scope.clickItem = ''
                $scope.nowCondition = condition
                var content = {
                    query_condition: condition
                };
                $scope.adjustInfo.SendResult_temp = 1 // 回到初始值
                adjustmentPlotInfoGet_main(content, function (response) {
                    if (response && response.length > 0) {
                        $scope.adjustInfo.adjustment_currently_main = [];
                        $scope.adjustInfo.adjustment_currently_main = response;
                        $scope.adjustInfo.adjustment_currently_detail = [];

                        //組合編號及名稱
                        for (var i = 0; i < $scope.adjustInfo.adjustment_currently_main.length; i++) {
                            var op_temp = $scope.adjustInfo.adjustment_currently_main[i].OpNo + "(" + $scope.adjustInfo.adjustment_currently_main[i].OPNAME + ")"
                            $scope.adjustInfo.adjustment_currently_main[i].op = op_temp;
                            var equipment_temp = $scope.adjustInfo.adjustment_currently_main[i].EquipmentNo + "(" + $scope.adjustInfo.adjustment_currently_main[i].EquipmentName + ")"
                            $scope.adjustInfo.adjustment_currently_main[i].equipment = equipment_temp;
                            var SendResult_temp
                            switch ($scope.adjustInfo.adjustment_currently_main[i].SendResult) {
                                case 0:
                                    SendResult_temp = `${$filter('translate')('B1801.queryList_main.column07')}`
                                    break;
                                case 1:
                                    SendResult_temp = `${$filter('translate')('B1801.queryList_main.column08')}`
                                    break;
                                case 2:
                                    SendResult_temp = `${$filter('translate')('B1801.queryList_main.column09')}`
                                    break;
                            }
                            $scope.adjustInfo.adjustment_currently_main[i].SendResult_display = SendResult_temp;
                        }
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        $scope.adjustInfo.adjustment_currently_main = [];
                        $scope.adjustInfo.adjustment_currently_detail = [];
                    }
                });
            }

            //頭檔帶入查詢身檔    
            $scope.itemClick = function (item) {
                if (item.RWOMESNO) {
                    $scope.clickItem = item
                    var content_detail = {
                        rwo_mesno: item.RWOMESNO
                    };
                }else {
                    var content_detail = {
                        rwo_mesno: item
                    };
                }
                adjustmentPlotInfoGet_detail(content_detail, function (response_detail) {
                    if (response_detail && response_detail.length > 0) {
                        $scope.adjustInfo.adjustment_currently_detail = [];
                        $scope.adjustInfo.adjustment_currently_detail = response_detail;
                        $scope.adjustInfo.adjustment_currently_detail_ori = response_detail;
                        $scope.adjustInfo.SendResult_temp = $scope.adjustInfo.adjustment_currently_detail_ori[0].SendResult;

                        //組合編號及名稱
                        for (var i = 0; i < $scope.adjustInfo.adjustment_currently_detail.length; i++) {
                            var user_temp = $scope.adjustInfo.adjustment_currently_detail[i].UserNo + "(" + $scope.adjustInfo.adjustment_currently_detail[i].USERNAME + ")"
                            $scope.adjustInfo.adjustment_currently_detail[i].user = user_temp; 
                            var op_temp = $scope.adjustInfo.adjustment_currently_detail[i].OpNo + "(" + $scope.adjustInfo.adjustment_currently_detail[i].OPNAME + ")"
                            $scope.adjustInfo.adjustment_currently_detail[i].op = op_temp;
                            var equipment_temp = $scope.adjustInfo.adjustment_currently_detail[i].EquipmentNo + "(" + $scope.adjustInfo.adjustment_currently_detail[i].EquipmentName + ")"
                            $scope.adjustInfo.adjustment_currently_detail[i].equipment = equipment_temp;
                        }

                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        $scope.adjustInfo.adjustment_currently_detail = [];
                    }
                });
            }

            //查詢調整歷程    
            $scope.record = function () {
                var content_record = {
                    flag: 2,
                    cur_LotNo: $scope.adjustInfo.adjustment_currently_detail[0].LotNo,
                    cur_OpNo: $scope.adjustInfo.adjustment_currently_detail[0].OpNo,
                    cur_EquipmentNo: $scope.adjustInfo.adjustment_currently_detail[0].EquipmentNo,
                    cur_RWOMESNO: $scope.adjustInfo.adjustment_currently_detail[0].RWOMESNO
                };
                adjustmentPlotInfoGet_process(content_record, function (response_record) {
                    if (response_record && response_record.length > 0) {
                        $scope.adjustInfo.adjustment_currently_record = response_record;

                        //組合編號及名稱
                        for (var i = 0; i < $scope.adjustInfo.adjustment_currently_record.length; i++) {
                            var user_temp = $scope.adjustInfo.adjustment_currently_record[i].UserNo + "(" + $scope.adjustInfo.adjustment_currently_record[i].USERNAME + ")"
                            $scope.adjustInfo.adjustment_currently_record[i].user = user_temp;
                            var op_temp = $scope.adjustInfo.adjustment_currently_record[i].OpNo + "(" + $scope.adjustInfo.adjustment_currently_record[i].OPNAME + ")"
                            $scope.adjustInfo.adjustment_currently_record[i].op = op_temp;
                            var equipment_temp = $scope.adjustInfo.adjustment_currently_record[i].EquipmentNo + "(" + $scope.adjustInfo.adjustment_currently_record[i].EquipmentName + ")"
                            $scope.adjustInfo.adjustment_currently_record[i].equipment = equipment_temp;
                        }

                        //開窗
                        $scope.recordopen($scope.adjustInfo.adjustment_currently_record);

                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    }
                });
            }

            //新增日結紀錄    
            $scope.add = function () {
                $scope.adjustInfo.adjustment_currently_add.LotNo = $scope.adjustInfo.adjustment_currently_detail[0].LotNo;
                $scope.adjustInfo.adjustment_currently_add.OpNo = $scope.adjustInfo.adjustment_currently_detail[0].OpNo;
                $scope.adjustInfo.adjustment_currently_add.EquipmentNo = $scope.adjustInfo.adjustment_currently_detail[0].EquipmentNo;
                $scope.adjustInfo.adjustment_currently_add.op = $scope.adjustInfo.adjustment_currently_detail[0].OpNo + "(" + $scope.adjustInfo.adjustment_currently_detail[0].OPNAME + ")";
                $scope.adjustInfo.adjustment_currently_add.equipment = $scope.adjustInfo.adjustment_currently_detail[0].EquipmentNo + "(" + $scope.adjustInfo.adjustment_currently_detail[0].EquipmentName + ")";
                $scope.adjustInfo.adjustment_currently_add.RWOMESNO = $scope.adjustInfo.adjustment_currently_detail[0].RWOMESNO;
                $scope.adjustInfo.adjustment_currently_add.ReportDate = $scope.adjustInfo.adjustment_currently_detail[0].ReportDate;
                $scope.adjustInfo.adjustment_currently_add.EMPTime_s = 0;
                $scope.adjustInfo.adjustment_currently_add.EQPTime_s = 0;
                $scope.adjustInfo.adjustment_currently_add.UserNo = "";
                $scope.adjustInfo.adjustment_currently_add.MoNo = $scope.adjustInfo.adjustment_currently_detail[0].MoNo;
                $scope.adjustInfo.adjustment_currently_add.QTY = 0;
                //傳入機時數量，校驗用，人時數量不可大於機時
                var QTY_EQP = 0;
                for (var i = 0; i < $scope.adjustInfo.adjustment_currently_detail.length; i++) {
                    //取得機時數量+多餘數量
                    if ($scope.adjustInfo.adjustment_currently_detail[i].ReportType == 1) {
                        QTY_EQP = Math.round($scope.adjustInfo.adjustment_currently_detail[i].QTY) + Math.round($scope.adjustInfo.adjustment_currently_detail[i].EXCESS_QTY);
                    }
                }
                $scope.adjustInfo.adjustment_currently_add.QTY_EQP = QTY_EQP;

                //開窗
                $scope.addopen([$scope.adjustInfo.adjustment_currently_add]);
            }

            //清除查詢紀錄    
            $scope.cancel = function () {
                $scope.adjustInfo.adjustment_currently_detail = [];
                $scope.adjustInfo.adjustment_currently_record = [];
                $scope.adjustInfo.adjustment_currently_add = [];
            }

            //修改送出
            $scope.confirm = function () {
                if ($scope.adjustInfo.adjustment_currently_detail.length) {
                    var QTY_EQP = 0;
                    var QTY_EMP_MAX = 0;
                    for (var i = 0; i < $scope.adjustInfo.adjustment_currently_detail.length; i++) {
                        $scope.adjustInfo.adjustment_currently_detail[i].EMPTime_s = Math.round($scope.adjustInfo.adjustment_currently_detail[i].EMPTime_s * 100) / 100;
                        $scope.adjustInfo.adjustment_currently_detail[i].EQPTime_s = Math.round($scope.adjustInfo.adjustment_currently_detail[i].EQPTime_s * 100) / 100;
                        //取得機時數量+多餘數量
                        if ($scope.adjustInfo.adjustment_currently_detail[i].ReportType == 1) QTY_EQP = Math.round($scope.adjustInfo.adjustment_currently_detail[i].QTY) + Math.round($scope.adjustInfo.adjustment_currently_detail[i].EXCESS_QTY);
                        //取得最大人時數量
                        if ($scope.adjustInfo.adjustment_currently_detail[i].ReportType == 0 && $scope.adjustInfo.adjustment_currently_detail[i].QTY > QTY_EMP_MAX) {
                            QTY_EMP_MAX = Math.round($scope.adjustInfo.adjustment_currently_detail[i].QTY);
                        }
                    }
                    var content_edit = {
                        flag: 1,
                        detail: $scope.adjustInfo.adjustment_currently_detail
                    };
                    if (QTY_EQP >= QTY_EMP_MAX) {
                        adjustmentPlotInfoGet_process(content_edit, function (response_edit) {
                            if (response_edit) {
                                $scope.$root.showToast($filter('translate')('B1801.msg.edit_success'));
                                var RWOMESNO_temp = $scope.adjustInfo.adjustment_currently_detail[0].RWOMESNO;
                                $scope.cancel();
                                $scope.itemClick(RWOMESNO_temp);
                            }
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('B1801.msg.qty_error_1') + QTY_EMP_MAX + $filter('translate')('B1801.msg.qty_error_2') + QTY_EQP);
                    }
                }
            };

            //用生產批號、作業站編號、設備編號等 取得頭檔資訊
            function adjustmentPlotInfoGet_main(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.daily_workreport_adjustment_info_get',
                    content: content,
                    success: function (data) {
                        feedback(data);
                    }
                });
            }

            //帶入頭檔資訊 取得查詢明細
            function adjustmentPlotInfoGet_detail(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.daily_workreport_adjustment_detail',
                    content: content,
                    success: function (data) {
                        feedback(data);
                    }
                });
            }

            //新增、修改、歷程
            function adjustmentPlotInfoGet_process(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.daily_workreport_adjustment_process',
                    content: content,
                    success: function (data) {
                        feedback(data);
                    }
                });
            }            

            //調整歷程開窗查詢
            $scope.recordopen = function (item) {
                $mdDialog.dialog(
                    'module/moduleB/program/B18/B1801/B1801_record.tmp.html',
                    function (dialog) {
                        return {
                            adjustment_currently_record: item,
                            adjustment_currently_record_top: item[0],
                            back: function () {
                                dialog.hide();
                            },
                            confirm: function () {
                                dialog.hide();
                            }
                        }
                    }
                );
            };

            //日期事件
            $scope.changeDate = function () {
                var date = moment(new Date()).format('YYYY-MM-DD');
                $datePicker.open(date, function (dialog) {
                    //confirm event
                    $scope.adjustInfo.reportdate = dialog.datePacker.pickDate;
                    $scope.adjustInfo.reportdate = moment($scope.adjustInfo.reportdate).format('YYYY-MM-DD');
                    $scope.search();
                    dialog.hide();
                }, function (dialog) {
                    //cancel event
                    $scope.adjustInfo.reportdate = null;
                    dialog.hide();
                }, {});

            };
            $scope.orderbychange  = function(mode){
                if($scope.order_by_mode.name != mode){
                    $scope.order_by_mode.name = mode;
                    $scope.order_by_mode.sort = false;
                }else{
                    if($scope.order_by_mode.sort)
                        $scope.order_by_mode.sort = false;
                    else
                        $scope.order_by_mode.sort = true;
                }
            }
            $scope.getPages = function(list, PageConfig, filterItem){
                if(!list){
                   //console.log();
                   if($scope.order_by_mode.name != "")
                    list =  $filter('orderBy')(list,$scope.order_by_mode.name,$scope.order_by_mode.sort);
                   var temp_list = list.filter(function(item, index, array){
                        var isOK = true,
                            keys = Object.keys(filterItem);
                        for(var i =0; i<keys.length;i++){
                            var key = keys[i];
                            if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                                if(item[key].toString().indexOf(filterItem[key]) == -1){
                                    isOK = false;
                                    break;
                                }
                            }
                        }
                        return isOK;
                    });
                    if(PageConfig){
                        if(temp_list.length != 0){
                            PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);
    
                            if(PageConfig.page >= PageConfig.total_page){
                                PageConfig.page = 0;
                            }
                            var index = PageConfig.page*PageConfig.page_count;
                            return temp_list.slice(index, index+PageConfig.page_count);
                        } else {
                            PageConfig.total_page = 1;
                            PageConfig.page = 0;
                        }
                    } else {
                        return temp_list;
                    }
                } else {
                    if($scope.order_by_mode.name != ""){
                        list =  $filter('orderBy')(list,$scope.order_by_mode.name,$scope.order_by_mode.sort);
                        return list;
                    } else {
                        return list;
                    }
    
                }
            };
            //日結開窗新增
            $scope.addopen = function (item) {
                $mdDialog.dialog(
                    'module/moduleB/program/B18/B1801/B1801_add.tmp.html',
                    function (dialog) {
                        return {
                            adjustment_currently_add: item,
                            user_no: "",
                            back: function () {
                                dialog.hide();
                            },
                            //人員開窗查詢
                            loadUserNo: function () {
                                $MMWService.showQueryListPNIG({
                                    page_mode: 'opm_user_no_info_get',
                                    pageRecord: 50,
                                    condition: [
                                        { name: $filter('translate')('B1801.addopen.column09'), column_name: 'UserNo', query_mode: '2', value: '' }
                                    ],
                                    header: [
                                        { label: $filter('translate')('B1801.addopen.column09'), code: 'user_no' },
                                        { label: $filter('translate')('B1801.addopen.column10'), code: 'user_name' }
                                    ],
                                    setCondition: function (conditions) {
                                        conditions.push(
                                            { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                        );
                                        return conditions;
                                    },
                                    selectCode: dialog.user_no || '',
                                    confirm: function (selectItem) {
                                        dialog.user_no = selectItem.user_no;
                                    }
                                });

                            },
                            confirm: function () {
                                var add_return_user = dialog.user_no;
                                var add_return = dialog.adjustment_currently_add.map(function (item) {
                                    return (item);
                                });
                                if (add_return_user == "") {
                                    $scope.$root.showAlert($filter('translate')('B1801.msg.userno_empty'));
                                } else if (add_return[0].EMPTime_s == "0") {
                                    $scope.$root.showAlert($filter('translate')('B1801.msg.EMPTime_s_empty'));
                                } else if (Math.round(add_return[0].QTY) > Math.round(add_return[0].QTY_EQP)) {
                                    $scope.$root.showAlert($filter('translate')('B1801.msg.qty_error_1') + add_return[0].QTY + $filter('translate')('B1801.msg.qty_error_2') + add_return[0].QTY_EQP);
                                } else {
                                    //成功送出
                                    var add_return_final = {
                                        LotNo: add_return[0].LotNo,
                                        OpNo: add_return[0].OpNo,
                                        ReportDate: add_return[0].ReportDate,
                                        EquipmentNo: add_return[0].EquipmentNo,
                                        EMPTime_s: Math.round(add_return[0].EMPTime_s * 100) / 100,
                                        EQPTime_s: $scope.adjustInfo.adjustment_currently_add.EQPTime_s,
                                        RWOMESNO: add_return[0].RWOMESNO,
                                        UserNo: add_return_user,
                                        MoNo: $scope.adjustInfo.adjustment_currently_detail[0].MONo,
                                        ReportType: 0, //人時=0;機時=1
                                        QTY: add_return[0].QTY
                                    };
                                    var content_add = {
                                        flag: 0,
                                        detail: [add_return_final]
                                    };
                                    var msg = $filter('translate')('B1801.msg.cofirm');
                                    $scope.$root.showConfirm(msg, function (confirm_dialog) {
                                        confirm_dialog.hide();
                                        adjustmentPlotInfoGet_process(content_add, function (response_add) {
                                            if (response_add) {
                                                $scope.$root.showToast($filter('translate')('B1801.msg.add_success'));
                                                $scope.cancel();
                                                $scope.itemClick(add_return[0].RWOMESNO);
                                            }
                                        });
                                        dialog.hide();
                                    });
                                }
                            }
                        }
                    }
                );
            };
            // 日結拋轉狀態調整
            $scope.changeState = function () {
                changeState_list = [],
                $mdDialog.dialog(
                    'module/moduleB/program/B18/B1801/B1801_changeState.tmp.html',
                    function (dialog) {
                        return {
                            changeState_list: changeState_list,
                            init: function(){ // 初始化
                                $MMWService.sendToServer({
                                    uri : 'ServicesSTD.Module_WIP.daily_workreport_tossing_adjustment_info_get',
                                    content : {MESNo:$scope.clickItem.RWOMESNO},
                                    success : function(data){
                                        data.forEach(item => {
                                            changeState_list.push(item)
                                        });
                                    }
                                });
                            },
                            back: function () {
                                dialog.hide();
                            },
                            confirm: function (item) {
                                $scope.$root.showConfirm($filter('translate')('B1801.changeStateOpen.showcomfirm'),function(confirm_dialog){
                                    // 未拋轉 0, 已拋轉 1, 拋轉失敗 2
                                    $MMWService.sendToServer({
                                        uri : 'ServicesSTD.Module_WIP.daily_workreport_tossing_adjustment_info_process',
                                        content : {SOURCE_NO:$scope.clickItem.RWOMESNO},
                                        success : function(data){
                                            confirm_dialog.hide()
                                            $scope.$root.showToast($filter('translate')('B1801.changeStateOpen.success'))
                                            dialog.hide();
                                            $scope.search($scope.nowCondition)
                                        }
                                    });
                                });
                            }
                        }
                    }
                );
            };

        }
    ]
});
